/**
 * 设置语言界面
 */

import React, {useState, useEffect} from 'react';
import {View, StyleSheet, TouchableOpacity, Alert} from 'react-native';

import {ListItem} from '@rneui/themed';
import {connect} from 'react-redux';
import {handleSetLang} from '@/store/action/lang';
import StorageUtils from '@/utils/storageUtils';
import {useTranslation} from 'react-i18next';

const SetLanguage = props => {
  const {t, i18n} = useTranslation();
  const {lang, langList, handleSetLang, navigation} = props;
  const [currentLang, setCurrentLang] = useState('zh');
  const getLocalLang = async () => {
    const localLang = await StorageUtils.getItem('APP_LANG');
    setCurrentLang(localLang || lang || 'zh');
  };

  useEffect(() => {
    navigation.setOptions({
      headerShown: true,
      headerBackVisible: true,
    });
    getLocalLang();
  }, []);
  const updateLanguage = lang => {
    Alert.alert(t('sys_tip'), t('sys_confirmChangeLanguage'), [
      {
        text: t('sys_cancel'),
        onPress: () => {},
        style: 'cancel',
      },
      {
        text: t('sys_confirm'),
        onPress: () => {
          const langType = lang.langType;
          handleSetLang(langType);
          i18n.changeLanguage(langType);
          setCurrentLang(langType);
        },
      },
    ]);
  };

  return (
    <View style={styles.container}>
      <View style={styles.container}>
        {langList.map(languageObj => {
          const {langType, langTranslate, pressFunc} = languageObj;
          const isCurrentLanguage = currentLang === langType;
          return (
            <TouchableOpacity
              key={langType}
              onPress={() => {
                updateLanguage(languageObj);
              }}>
              <ListItem bottomDivider>
                <ListItem.Content>
                  <ListItem.Title
                    style={{color: isCurrentLanguage ? '#1677ff' : '#666'}}>
                    {langTranslate}
                  </ListItem.Title>
                </ListItem.Content>
              </ListItem>
            </TouchableOpacity>
          );
        })}
      </View>
    </View>
  );
};

export default connect(
  state => ({
    lang: state.lang.lang,
    langList: state.lang.langList,
  }),
  dispatch => ({
    handleSetLang: lang => dispatch(handleSetLang(lang)),
  }),
)(SetLanguage);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F3F4F8',
  },
});
